package com.example.apple.baseadapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by apple on 2017/5/29.
 */

public class MainAdapter extends BaseAdapter {
    private List<Person> persons;

    public MainAdapter(List<Person> persons) {
        this.persons = persons;
    }

    /**
     * 通过构造方法传进去
     * */

    @Override
    public int getCount() {
        return persons==null?0:persons.size();
    }

    @Override
    public Object getItem(int i) {
        return persons.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        /**
         * 判断convertView是否为空
         * */
        if(convertView==null){
            Context context= parent.getContext();
            convertView= LayoutInflater.
                    from(context).inflate(R.layout.item_main,parent,false);
            viewHolder=new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else{
            /**
             * 直接取出viewHoleder
             * */
        viewHolder= (ViewHolder) convertView.getTag();
        }

        viewHolder.mImageView.setImageResource(persons.get(i).getIcon());
        viewHolder.mTextView.setText(persons.get(i).getName());
        /**
         * 使用ViewHolder可以不用操作以下代码
         * */
//        /**
//         * 设置数据  取到给ImageView
//         * */
//        ImageView imageView= (ImageView) convertView.findViewById(R.id.item_icon);
//        imageView.setImageResource(persons.get(i).getIcon());
//
//        TextView textView= (TextView) convertView.findViewById(R.id.item_name);
//        textView.setText(persons.get(i).getName());
        /**
         * 返回行布局
         * */
        return convertView;
    }
    private class ViewHolder{
        ImageView mImageView;
        TextView  mTextView;
/**
 *构造方法直接将行布局传进去
 * */
        public ViewHolder( View itemView) {
          mImageView= (ImageView) itemView.findViewById(R.id.item_icon);
          mTextView= (TextView) itemView.findViewById(R.id.item_name);
        }
    }
    }

